/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: user
 * Date: 2024-05-12
 * Time: 15:25
 */
public class HashBuck {
    public static class Node{

        public int key;
        public int val ;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }
    public Node[] array;
    public int usedSize;
    public double loadFactor = 0.75;

    public HashBuck() {
        this.array = new Node[10];
    }
    public void put(int key,int val){
        int index = key % array.length;
        Node cur = array[index];
        //1. 遍历当前链表 是否存在当前值
        while(cur != null){
            if(cur.key == key){
                cur.val = val;
            }
            cur = cur.next;
        }
        //2. 说明 没有当前值，此时进行 头插
        Node node = new Node(key,val);
        node.next = array[index];
        array[index] = node;
        usedSize++;
        //3.判断是否要扩容
       if (loadFactorCount() >= loadFactor){
         resize();
       }
    }
    public void resize(){
        Node[] newArray = new Node[array.length * 2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while(cur != null){
                int newIndex = cur.key % newArray.length;
                Node curN = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curN;
            }
        }
        array = newArray;
    }
    public double loadFactorCount(){
        return usedSize * 1.0 / array.length;
    }
    public int get(int key){
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null){
            if(cur.key == key){
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
